﻿using Antlr4.Runtime.Tree;
using NCalc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace ConsoleNCalcu
{
    public  class Program
    {
       
      


        static void Main(string[] args)
        {

           // double[] x = { 1, 2, 3 };
           // double[] y = { 60, 35, 11 };
           // var result = MathNet.Numerics.Fit.Line(x, y);
           //// result.B
           //     Console.WriteLine(result.B);
           // Console.WriteLine(result.ToString());
           // Console.ReadLine();




            string strConfig = @"{""analysisModels"":[""energyStatus"",""effortLevel"",""fatigueStatus"",""emotionManager"",""easyObedient"",""activeMind"",""focusOnInvestment"",""enterprising""],""statusCodes"":[""positive"",""serious"",""normal"",""common"",""relax"",""rest"",""-1""],""eventPointsUp"":[""difficult"",""detail"",""thinking"",""focus"",""downcast"",""nervous""],""eventPointsDown"":[""fatigue"",""helpless"",""worry"",""emotion"",""excite""]}";

            string strNewConfig = @"{""analysisModels"":[""energyStatus"",""effortLevel"",""fatigueStatus"",""emotionManager"",""easyObedient"",""activeMind"",""focusOnInvestment"",""enterprising""],""statusModels"":{""status"":[""positive"",""serious"",""normal"",""common"",""relax"",""rest"",""-1""],},""eventPoints"":{""up"":[""difficult"",""detail"",""thinking"",""focus"",""downcast"",""nervous""],""down"":[""fatigue"",""helpless"",""worry"",""emotion"",""excite""]},""periodStatusCode"":""periodStatus"",""totalStatusCode"":""totalStatus""}";
            
            #region strFactor
            string strFactor = @"[
	{
		""name"": ""总体"",
		""code"": ""totaldes"",
		""formula"": """",
		""standard"": """",
		""result"": ""[\""总体上\"",\""大体上\"",\""大致\"",\""综合来看\"",\""基本\"",\""多数\"",\""整体\"",\""数据分析来看\"",\""结果分析来看\"",\""评估提示\""]"",
		""pattern"": """"
	},
	{
		""name"": ""谓语1"",
		""code"": ""predicate1"",
		""formula"": """",
		""standard"": """",
		""result"": ""[\""处于\"",\""是\"",\""为\""]"",
		""pattern"": """"
	},
	{
		""name"": ""谓语2"",
		""code"": ""predicate2"",
		""formula"": """",
		""standard"": """",
		""result"": ""[\""出现\"",\""有\"",\""呈现\""]"",
		""pattern"": """"
	},
	{
		""name"": ""连接词"",
		""code"": ""connect"",
		""formula"": """",
		""standard"": """",
		""result"": ""[\""并且\"",\""且\"",\""同时\""]"",
		""pattern"": """"
	},
	{
		""name"": ""趋势"",
		""code"": ""status_trend"",
		""formula"": """",
		""standard"": ""-0.1|0.1"",
		""result"": ""[\""处于下行趋势\"",\""逐渐下降\"",\""有下降趋势\""]|[\""比较稳定\"",\""相对平稳\"",\""基本保持不变\""]|[\""趋向积极\"",\""逐渐变好\"",\""呈上升趋势\""]"",
		""pattern"": ""<=""
	},
	{
		""name"": ""频率"",
		""code"": ""frequence"",
		""formula"": """",
		""standard"": ""25|50"",
		""result"": ""[\""偶尔\"",\""少许\"",\""偶发\"",\""较少\"",\""少量\"",\""稍许\""]|[\""间歇\"",\""断断续续\"",\""部分\"",\""一定\"",\""些许\"",\""片段\""]|[\""持续\"",\""不断\"",\""连续发生\"",\""明显\"",\""显著\"",\""较多\""]"",
		""pattern"": ""<=""
	},
	{
		""name"": ""频率"",
		""code"": ""extevent_frequence"",
		""formula"": """",
		""standard"": ""25|50"",
		""result"": ""[\""偶尔\"",\""少许\"",\""偶发\"",\""较少\"",\""少量\"",\""稍许\""]|[\""间歇\"",\""断断续续\"",\""部分\"",\""一定\"",\""些许\"",\""片段\""]|[\""持续\"",\""不断\"",\""连续发生\"",\""明显\"",\""显著\"",\""较多\""]"",
		""pattern"": ""<=""
	},
	{
		""name"": ""烧脑"",
		""code"": ""difficult"",
		""formula"": """",
		""standard"": """",
		""result"": ""[\""烧脑\"",\""费脑\"",\""深入分析\"",\""绞尽脑汁\""]"",
		""pattern"": """"
	},
	{
		""name"": ""细节"",
		""code"": ""detail"",
		""formula"": """",
		""standard"": """",
		""result"": ""[\""细节\"",\""仔细\"",\""细心观察\"",\""洞察\""]"",
		""pattern"": """"
	},
	{
		""name"": ""思考"",
		""code"": ""thinking"",
		""formula"": """",
		""standard"": """",
		""result"": ""[\""思考\"",\""动脑\"",\""思索\"",\""琢磨\""]"",
		""pattern"": """"
	},
	{
		""name"": ""专心"",
		""code"": ""focus"",
		""formula"": """",
		""standard"": """",
		""result"": ""[\""专心\"",\""专注\"",\""聚精会神\"",\""全神贯注\""]"",
		""pattern"": """"
	},
	{
		""name"": ""低落"",
		""code"": ""downcast"",
		""formula"": """",
		""standard"": """",
		""result"": ""[\""低落\"",\""消沉\"",\""有点压抑\"",\""沉闷\""]"",
		""pattern"": """"
	},
	{
		""name"": ""紧张"",
		""code"": ""nervous"",
		""formula"": """",
		""standard"": """",
		""result"": ""[\""紧张\"",\""着急\"",\""神经紧绷\"",\""不安感\""]"",
		""pattern"": """"
	},
	{
		""name"": ""疲劳"",
		""code"": ""fatigue"",
		""formula"": """",
		""standard"": """",
		""result"": ""[\""疲劳\"",\""疲惫\"",\""疲乏\"",\""疲倦\""]"",
		""pattern"": """"
	},
	{
		""name"": ""无奈"",
		""code"": ""helpless"",
		""formula"": """",
		""standard"": """",
		""result"": ""[\""无奈\"",\""无可奈何\"",\""无助\"",\""无力感\""]"",
		""pattern"": """"
	},
	{
		""name"": ""担忧"",
		""code"": ""worry"",
		""formula"": """",
		""standard"": """",
		""result"": ""[\""担忧\"",\""担心\"",\""情绪起伏\"",\""顾虑\""]"",
		""pattern"": """"
	},
	{
		""name"": ""情感"",
		""code"": ""emotion"",
		""formula"": """",
		""standard"": """",
		""result"": ""[\""情感\"",\""情感体验\"",\""触动\"",\""心情变化\""]"",
		""pattern"": """"
	},
	{
		""name"": ""激动"",
		""code"": ""excite"",
		""formula"": """",
		""standard"": """",
		""result"": ""[\""激动\"",\""焦躁\"",\""焦灼\"",\""心急\""]"",
		""pattern"": """"
	},
	{
		""name"": ""精力水平"",
		""code"": ""enegylevel"",
		""formula"": ""energyStatus*3-fatigueStatus*1"",
		""standard"": ""2|2.6"",
		""result"": ""[\""普通\"",\""一般\"",\""略低\""]|[\""中等\"",\""正常\"",\""尚可\""]|[\""充沛\"",\""充足\"",\""较好\""]"",
		""pattern"": """"
	},
	{
		""name"": ""大脑活动"",
		""code"": ""brainactivity"",
		""formula"": ""focusOnInvestment*0.42+effortLevel*0.2+activeMind*0.35"",
		""standard"": ""1.5|1.8"",
		""result"": ""[\""不多\"",\""一般\"",\""偏少\""]|[\""适度\"",\""正常\"",\""适中\""]|[\""活跃\"",\""敏捷\"",\""激烈\""]"",
		""pattern"": """"
	},
	{
		""name"": ""情绪特质"",
		""code"": ""emotiontrait"",
		""formula"": ""enterprising*0.8+emotionManager*0.1+easyObedient*0.1"",
		""standard"": ""1.4|1.9"",
		""result"": ""[\""率直\"",\""敏感\"",\""感性\""]|[\""平和求稳\"",\""克制稳定\"",\""稳健\""]|[\""争胜要强\"",\""进取沉稳\"",\""追求上进\""]"",
		""pattern"": """"
	},
	{
		""name"": ""总体趋势"",
		""code"": ""total_trend"",
		""formula"": """",
		""standard"": ""-0.01|0.05"",
		""result"": ""[\""处于下行趋势\"",\""逐渐下降\"",\""有下降趋势\""]|[\""比较稳定\"",\""相对平稳\"",\""基本保持不变\""]|[\""趋向积极\"",\""逐渐变好\"",\""呈上升趋势\""]"",
		""pattern"": """"
	},
	{
		""name"": ""精力水平趋势"",
		""code"": ""enegylevel_trend"",
		""formula"": """",
		""standard"": ""-0.01|0.01"",
		""result"": ""[\""处于下行趋势\"",\""逐渐下降\"",\""有下降趋势\""]|[\""比较稳定\"",\""相对平稳\"",\""基本保持不变\""]|[\""趋向积极\"",\""逐渐变好\"",\""呈上升趋势\""]"",
		""pattern"": """"
	},
	{
		""name"": ""大脑活动趋势"",
		""code"": ""brainactivity_trend"",
		""formula"": """",
		""standard"": ""-0.001|0.01"",
		""result"": ""[\""处于下行趋势\"",\""逐渐下降\"",\""有下降趋势\""]|[\""比较稳定\"",\""相对平稳\"",\""基本保持不变\""]|[\""趋向积极\"",\""逐渐变好\"",\""呈上升趋势\""]"",
		""pattern"": """"
	},
	{
		""name"": ""情绪特质"",
		""code"": ""emotiontrait_trend"",
		""formula"": """",
		""standard"": ""-0.001|0.001"",
		""result"": ""[\""处于下行趋势\"",\""逐渐下降\"",\""有下降趋势\""]|[\""比较稳定\"",\""相对平稳\"",\""基本保持不变\""]|[\""趋向积极\"",\""逐渐变好\"",\""呈上升趋势\""]"",
		""pattern"": """"
	},
	{
		""name"": ""努力程度"",
		""code"": ""effortLevel"",
		""formula"": ""(thinking*1+thinkingActivity*1+lowFlow*1+singleMindedness*1+lfn*0.15)*100/16+max(0,(thinking-5)*10)+max(0,(lowFlow-5)*10)+max(0,(singleMindedness-5)*10)"",
		""standard"": ""50|80"",
		""result"": ""1|2|3"",
		""pattern"": """"
	},
	{
		""name"": ""专注投入"",
		""code"": ""focusOnInvestment"",
		""formula"": ""(lowFlow*2.1+singleMindedness*2.3+midFlow*5+highFlow*8)*100/8+max(0,(singleMindedness-5)*10)"",
		""standard"": ""50|80"",
		""result"": ""1|2|3"",
		""pattern"": """"
	},
	{
		""name"": ""好胜进取"",
		""code"": ""enterprising"",
		""formula"": ""(impatient*3.5+worryTrait*5+crisisSense*0.8+thinkingActivity*0.8)*100/10+max(0,(impatient-5)*10)+max(0,(worryTrait-5)*10)"",
		""standard"": ""50|80"",
		""result"": ""1|2|3"",
		""pattern"": """"
	},
	{
		""name"": ""情绪管理"",
		""code"": ""emotionManager"",
		""formula"": ""100-(emotionalActivity*0.8+emotionalStress*1+anxietyTrait*1+delicateSensitive*1+midMoodWave*0.8+highMoodWave*0.8+innerHelplessness*1+innerResistance*1)*100/6+max(0,(emotionalStress-5)*10)+max(0,(anxietyTrait-5)*10)+max(0,(innerHelplessness-5)*5)+max(0,(innerResistance-5)*8)"",
		""standard"": ""30|60"",
		""result"": ""1|2|3"",
		""pattern"": """"
	},
	{
		""name"": ""随和顺从"",
		""code"": ""easyObedient"",
		""formula"": ""100-(worry*1+worryTrait*1+delicateSensitive*1+midMoodWave*0.8+highMoodWave*0.8+innerHelplessness*1+innerResistance*1)*100/6+max(0,(worry-5)*20)+max(0,(worryTrait-5)*10)+max(0,(delicateSensitive-5)*10)"",
		""standard"": ""30|60"",
		""result"": ""1|2|3"",
		""pattern"": """"
	},
	{
		""name"": ""思维活跃"",
		""code"": ""activeMind"",
		""formula"": ""(thinkingActivity*0.5+thinking*1.4+lowFlow*1.3+singleMindedness*1.8+mentalStress*4)*100/5+max(0,(thinking-5)*5)+max(0,(lowFlow-5)*8)+max(0,(singleMindedness-5)*10)+max(0,(mentalStress-5)*10)"",
		""standard"": ""50|80"",
		""result"": ""1|2|3"",
		""pattern"": """"
	},
	{
		""name"": ""疲劳状态"",
                ""code"": ""fatigueStatus"",
                ""formula"": ""(crisisSense*2+mentalFatigue*6+visualFatigue*6+lowDepress*6+midDepress*8+highDepress*10-lfn*0.1)*100/34+max(0,(mentalFatigue-5)*10)+max(0,(lowDepress-5)*10)+max(0,(midDepress-5)*10)+max(0,(highDepress-5)*10)"",
                ""standard"": ""17|40|85|95"",
                ""result"": ""1|2|3|4|5"",
                ""pattern"": """"
	},
	{
		""name"": ""精神面貌"",
		""code"": ""energyStatus"",
		""formula"": ""(lfn*0.2-mentalFatigue*2.5-visualFatigue*1+thinkingActivity*1.8+crisisSense*1.8+lowAnxiety*0.8+midAnxiety*1+ highAnxiety*1-lowDepress*1.2-midDepress*1.2-highDepress*1.5)*100/30 + max(0,(thinkingActivity-5)*3)+max(0,(crisisSense-5)*5)+max(0,(highAnxiety-5)*5) - max(0,(lowDepress-5)*10)"",
		""standard"": ""50|80"",
		""result"": ""1|2|3"",
		""pattern"": """"
	},
	{
		""name"": ""状态分值"",
		""code"": ""statusScore"",
		""formula"": """",
		""standard"": ""6|5|4|3|2|1"",
		""result"": ""[\""positive\""]|[\""serious\""]|[\""normal\""]|[\""common\""]|[\""relax\""]|[\""rest\""]|[\""-1\""]"",
		""pattern"": """"
	}
]";
            
            string strModel = @"[{""name"":""状态定性（3min）"",""code"":""statusQualitative"",""related_cfactors"":{""positive"":{""main"":[""lowFlow"",""midFlow"",""highFlow"",""singleMindedness"",""mentalStress"",""thinking"",""highAnxiety""],""second"":[""midAnxiety"",""impatient""],""other"":[],""maincount"":2,""perctage"":0.6},""serious"":{""main"":[""thinking"",""thinkingActivity"",""highAnxiety""],""second"":[""impatient"",""lowFlow"",""singleMindedness"",""midAnxiety""],""other"":[],""maincount"":2,""perctage"":0.6},""normal"":{""main"":[""thinkingActivity"",""crisisSense"",""midAnxiety""],""second"":[""thinking"",""lowFlow"",""singleMindedness"",""highAnxiety"",""lowAnxiety""],""other"":[],""maincount"":2,""perctage"":0.6},""common"":{""main"":[""crisisSense"",""lowAnxiety""],""second"":[""thinkingActivity"",""midAnxiety""],""other"":[],""maincount"":2,""perctage"":0.6},""relax"":{""main"":[],""second"":[""lowDepress"",""midDepress"",""highDepress"",""crisisSense""],""other"":[],""maincount"":2,""perctage"":0.6},""rest"":{""main"":[""lowDepress"",""midDepress"",""highDepress"",""mentalFatigue""],""other"":[],""second"":[],""maincount"":2,""perctage"":0.6}}},
{""name"":""状态定量（3min）"",""code"":""statusQuantitative"",""related_cfactors"":{""numeric_cols"":[""thinking"",""lowFlow"",""midFlow"",""highFlow"",""singleMindedness"",""lowAnxiety"",""midAnxiety"",""highAnxiety"",""lowDepress"",""midDepress"",""highDepress"",""thinkingActivity"",""mentalStress"",""impatient"",""anxietyTrait"",""crisisSense"",""mentalFatigue""],""weights"":{""lfn"":0.2,""thinking"":2,""lowFlow"":2,""midFlow"":2,""highFlow"":2,""singleMindedness"":2,""lowAnxiety"":0.4,""midAnxiety"":1.1,""highAnxiety"":1.6,""lowDepress"":-0.8,""midDepress"":-2,""highDepress"":-8,""thinkingActivity"":1.5,""mentalStress"":50,""impatient"":2,""anxietyTrait"":1,""crisisSense"":1,""mentalFatigue"":-1},""scores"":[75,60,50,35,25],""status_order"":[""positive"",""serious"",""normal"",""common"",""relax"",""rest""]}},
{""name"":""标记点（3min）"",""code"":""eventPoints"",""related_cfactors"":{""event_order"":{""up"":[{""difficult"":""funcontinuous_highFlowSet >= 1 or funcontinuous_midFlowSet >= 2""},{""detail"":""funcontinuous_singleMindednessSet >= 4""},{""focus"":""funcontinuous_lowFlowSet >= 3""},{""thinking"":""funcontinuous_thinkingSet >= 3""},{""nervous"":""funcontinuous_anxietyTraitSet >= 4 or funcontinuous_highAnxietySet >= 4""},{""downcast"":""funcontinuous_midDepressSet >= 4""}],""down"":[{""fatigue"":""funcontinuous_mentalFatigueSet >= 4 or funcontinuous_visualFatigueSet >= 8""},{""helpless"":""funcontinuous_innerHelplessnessSet >= 2 or funcontinuous_innerResistanceSet >= 2""},{""worry"":""funcontinuous_worryTraitSet >= 3 or funcontinuous_highMoodWaveSet >= 3""},{""emotion"":""funcontinuous_emotionalActivitySet >= 4 or funcontinuous_delicateSensitiveSet >= 3""},{""excite"":""funcontinuous_highMoodWaveSet >= 3 or funcontinuous_highAnxietySet >= 4""}]}}},
{""name"":""状态总评（15min）"",""code"":""periodStatus"",""related_cfactors"":""time{totaldes}{predicate1}{status}的状态，{connect}状态{status_trend}，其中{predicate2}{keyevent}，并伴随{extevent}。""},
{""name"":""事后总评"",""code"":""totalStatus"",""related_cfactors"":""{totaldes}{predicate1}{status}的状态，{connect}状态{total_trend}。精力水平{enegylevel}，{enegylevel_trend}；大脑活动{brainactivity}，{brainactivity_trend}；情绪特质{emotiontrait}，并且{emotiontrait_trend}。其中{predicate2}{keyevent}，并伴随{extevent}。""}]";

         
            string str7 = @"{""adultEpilepsySet"":[0,0,0,0,0,0],""anginaSet"":[-2,-2,-2,-2,-2,-2],""highAnxietySet"":[-2,-2,-2,-2,-2,1],""midAnxietySet"":[-2,-2,-2,-2,-2,-1],""lowAnxietySet"":[-2,-2,-2,-2,-2,-1],""anxietyTraitSet"":[-2,-2,-2,-2,-2,-2],""bloodOxygenSet"":[0,0,0,0,0,0],""singleMindednessSet"":[-2,-2,-2,-2,-2,-2],""childrenEpilepsySet"":[0,0,0,0,0,0],""chronicPainSet"":[-2,-2,-2,-2,-2,-2],""mentalStressSet"":[-2,-2,-2,-2,-2,-2],""thinkingActivitySet"":[-2,-2,-2,-2,-2,-2],""coronaryAtherosclerosisSet"":[-2,-2,-2,-2,-2,-2],""coronaryDiseaseSet"":[-2,-2,-2,-2,-2,-2],""highCrossOutSet"":[-2,-2,-2,-2,-2,-2],""lowCrossOutSet"":[-2,-2,-2,-2,-2,-2],""highDepressSet"":[-2,-2,-2,-2,-2,-2],""midDepressSet"":[-2,-2,-2,-2,-2,-2],""lowDepressSet"":[-2,-2,-2,-2,-2,-2],""diabetesType1Set"":[-2,-2,-2,-2,-2,-2],""diabetesType2Set"":[-2,-2,-2,-2,-2,-2],""drunkSet"":[-2,-2,-2,-2,-2,-2],""drunk2Set"":[-2,-2,-2,-2,-2,-2],""emotionalStressSet"":[-2,-2,-2,-2,-2,-2],""emotionalActivitySet"":[-2,-2,-2,-2,-2,-2],""erectileDysfunctionSet"":[0,0,0,0,0,0],""essentialHypertensionSet"":[-2,-2,-2,-2,-2,-2],""midFeverSet"":[-2,-2,-2,-2,-2,-2],""lowFeverSet"":[-2,-2,-2,-2,-2,-2],""highFlowSet"":[-2,-2,-2,-2,-2,-2],""midFlowSet"":[-2,-2,-2,-2,-2,-2],""lowFlowSet"":[-2,-2,-2,-2,-2,-2],""heartFailureSet"":[-2,-2,-2,-2,-2,-2],""heartRateTenAvgSet"":[78,83,83,82,85,84],""highHeroinAddictionSet"":[-1,-1,-1,-1,-1,-1],""lowHeroinAddictionSet"":[-1,-1,-1,-1,-1,-1],""thinkingSet"":[-1,-1,-1,-1,-1,-1],""highMoodWaveSet"":[-1,-1,-1,-1,-1,-1],""midMoodWaveSet"":[-1,-1,-1,-1,-1,-1],""lfnSet"":[31,30,38,55,64,77],""lfnAvgSet"":[35,33,35,39,43,48],""meanRateSet"":[78,77,77,80,81,83],""mentalFatigueSet"":[-2,-2,-2,-2,-2,-1],""delicateSensitiveSet"":[-2,-2,-2,-2,-2,-2],""nocturnalHypoglycemiaSet"":[0,0,0,0,0,0],""onLineGameAddictionSet"":[-2,-2,-2,-2,-2,-2],""ruminationSet"":[-2,-2,-2,-2,-2,-2],""highShiYingLevelSet"":[-1,-1,-1,-1,-1,-1],""midShiYingLevelSet"":[-1,-1,-1,-1,-1,-1],""lowShiYingLevelSet"":[-1,-1,-1,-1,-1,-1],""stimPainSet"":[-2,-2,-2,-2,1,1],""strokeSet"":[-2,-2,-2,-2,-2,-2],""suddenCardiacDeathSet"":[-2,-2,-2,-2,-2,-2],""impatientSet"":[-2,-2,-2,-2,-2,-2],""crisisSenseSet"":[-2,-2,-2,-2,-2,-2],""visualFatigueSet"":[-2,-2,-1,-1,-1,-1],""worrySet"":[-2,-2,-2,-2,-2,-2],""worryTraitSet"":[-2,-2,-2,-2,-2,-2],""innerResistanceSet"":[-1,-1,-1,-1,-1,-1],""innerHelplessnessSet"":[-1,-1,-1,-1,-1,-1],""sleepStage"":[4],""drowsinessLevel"":[0]}";


            #endregion




           
        //    CsharpScript.LoadConfiguration(strConfig, strFactor, strModel);
            CsharpScript.LoadConfiguration(strNewConfig, strFactor, strModel);
            

            string json_string = @"[[{'up': [{'eventCode': 'difficult', 'index': 2}, {'eventCode': 'focus', 'index': 2}, {'eventCode': 'thinking', 'index': 2}]}, {'down': [{'eventCode': 'helpless', 'index': 2}, {'eventCode': 'worry', 'index': 2}, {'eventCode': 'emotion', 'index': 2}, {'eventCode': 'excite', 'index': 2}]}],
 [{'up': [{'eventCode': 'difficult', 'index': 2}, {'eventCode': 'focus', 'index': 2}, {'eventCode': 'thinking', 'index': 2}]}, {'down': [{'eventCode': 'helpless', 'index': 2}, {'eventCode': 'worry', 'index': 2}, {'eventCode': 'emotion', 'index': 2}, {'eventCode': 'excite', 'index': 2}]}],
[{'up': [{'eventCode': 'difficult', 'index': 2}, {'eventCode': 'focus', 'index': 2}, {'eventCode': 'thinking', 'index': 2}]}, {'down': [{'eventCode': 'helpless', 'index': 2}, {'eventCode': 'worry', 'index': 2}, {'eventCode': 'emotion', 'index': 2}, {'eventCode': 'excite', 'index': 2}]}], 
[{'up': [{'eventCode': 'difficult', 'index': 2}, {'eventCode': 'focus', 'index': 2}, {'eventCode': 'thinking', 'index': 2}]}, {'down': [{'eventCode': 'helpless', 'index': 2}, {'eventCode': 'worry', 'index': 2}, {'eventCode': 'emotion', 'index': 2}, {'eventCode': 'excite', 'index': 2}]}], 
[{'up': [{'eventCode': 'difficult', 'index': 2}, {'eventCode': 'focus', 'index': 2}, {'eventCode': 'thinking', 'index': 2}]}, {'down': [{'eventCode': 'helpless', 'index': 2}, {'eventCode': 'worry', 'index': 2}, {'eventCode': 'emotion', 'index': 2}, {'eventCode': 'excite', 'index': 2}]}] ]";

            string json = @"{ ' \
              '""effortLevel"": [3,2,3,3,2,1,2,2,2,3,3,2,3,2,3,2,3,3,3,3,3,3,2,2,3,1,2,3,2,3,3,2,2,2,2],' \
              '""focusOnInvestment"": [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1,1],' \
              '""enterprising"": [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,3,3,3,2,3,3,3,3,3,3,3,3,3,1,1,1,1],' \
              '""emotionManager"": [3,3,3,3,3,1,1,1,1,1,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,1,1,1,1,1],' \
              '""easyObedient"": [3,3,3,3,3,3,3,2,3,2,3,3,3,2,3,3,3,3,3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1],' \
              '""activeMind"": [1,1,3,3,1,1,1,1,1,3,3,1,3,2,3,1,3,3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1,2],' \
              '""fatigueStatus"": [1,1,1,1,1,2,2,1,2,1,1,2,1,2,2,1,2,1,2,2,2,1,2,1,1,2,2,1,1,1,1,1,1,1,1],' \
              '""energyStatus"": [2,2,2,3,2,2,2,2,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,1,1,1]}";

            json = json.Replace("' \\\r\n              '", "");

            string allOneMinutesList = @"{ ""effortLevel"": [3,2,3,3,2,1,2,2,2,3,3,2,3,2,3,2,3,3,3,3,3,3,2,2,3,1,2,3,2,3,3,2,2,2,2],""focusOnInvestment"": [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1,1],""enterprising"": [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,3,3,3,2,3,3,3,3,3,3,3,3,3,1,1,1,1],""emotionManager"": [3,3,3,3,3,1,1,1,1,1,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,1,1,1,1,1],""easyObedient"": [3,3,3,3,3,3,3,2,3,2,3,3,3,2,3,3,3,3,3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1],""activeMind"": [1,1,3,3,1,1,1,1,1,3,3,1,3,2,3,1,3,3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1,2],""fatigueStatus"": [1,1,1,1,1,2,2,1,2,1,1,2,1,2,2,1,2,1,2,2,2,1,2,1,1,2,2,1,1,1,1,1,1,1,1],""energyStatus"": [2,2,2,3,2,2,2,2,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,1,1,1]}";


            string json_stringAll = @"[[{'up': [{'eventCode': 'difficult', 'index': 2},
                                                             {'eventCode': 'detail', 'index': 2},
                                                             {'eventCode': 'nervous', 'index': 2}]},
                                                     {'down': [{'eventCode': 'excite', 'index': 2}]}],
              [{'up': [{'eventCode': 'detail', 'index': 2},
                                                             {'eventCode': 'focus', 'index': 2},
                                                             {'eventCode': 'thinking', 'index': 2}]},
                                                     {'down': [{'eventCode': 'emotion', 'index': 2},
                                                               {'eventCode': 'excite', 'index': 2}]}],
              [{'up': [{'eventCode': 'nervous', 'index': 2},
                                                             {'eventCode': 'focus', 'index': 2},
                                                             {'eventCode': 'detail', 'index': 2}]},
                                                     {'down': [{'eventCode': 'helpless', 'index': 2},
                                                               {'eventCode': 'excite', 'index': 2}]}],
               [{'up': [{'eventCode': 'difficult', 'index': 2},
                                                             {'eventCode': 'detail', 'index': 2},
                                                             {'eventCode': 'thinking', 'index': 2}]},
                                                     {'down': [{'eventCode': 'helpless', 'index': 2},
                                                               {'eventCode': 'worry', 'index': 2},
                                                               {'eventCode': 'excite', 'index': 2}]}],
               [{'up': [{'eventCode': 'difficult', 'index': 2},
                                                             {'eventCode': 'detail', 'index': 2},
                                                             {'eventCode': 'nervous', 'index': 2}]},
                                                     {'down': [{'eventCode': 'excite', 'index': 2}]}],
               [{'up': [{'eventCode': 'difficult', 'index': 2},
                                                             {'eventCode': 'detail', 'index': 2},
                                                             {'eventCode': 'nervous', 'index': 2}]},
                                                     {'down': [{'eventCode': 'excite', 'index': 2}]}],
               [{'up': [{'eventCode': 'difficult', 'index': 2},
                                                             {'eventCode': 'detail', 'index': 2},
                                                             {'eventCode': 'nervous', 'index': 2}]},
                                                     {'down': [{'eventCode': 'excite', 'index': 2}]}],
              [{'up': [{'eventCode': 'difficult', 'index': 2},
                                                             {'eventCode': 'focus', 'index': 2},
                                                             {'eventCode': 'detail', 'index': 2}]},
                                                     {'down': [{'eventCode': 'helpless', 'index': 2},
                                                               {'eventCode': 'excite', 'index': 2}]}]
               ]";


            //  string status_period_json = @"[{""status"":""positive""},{""status"":""serious""},{""status"":""normal""},{""status"":""normal""},{""status"":""common""}]";

            string status_period_json = @"[{""status"":""positive""},{""status"":""serious""},{""status"":""normal""},{""status"":""normal""},{""status"":""common""}]";



            string status_total_json = @"[{""status"":""normal""},{""status"":""normal""},{""status"":""normal""},{""status"":""normal""},{""status"":""positive""},{""status"":""positive""},{""status"":""positive""},{""status"":""positive""}]";


            //  CsharpScript.ParseSetting();

            //15 分钟    
            //      string periodResult =  CsharpScript.AnalysisModel(json_string);          

            // 结束
            //   CsharpScript.analysis_model_total("a,b", json_stringAll, allOneMinutesList);


            string json_strtest = @"[[{""up"":[]},{""down"":[]}],[{""up"":[]},{""down"":[]}],[{""up"":[]},{""down"":[]}],[{""up"":[]},{""down"":[]}],[{""up"":[{""eventCode"":""thinking"",""index"":3}]},{""down"":[]}]]";
            string status_test= @"[{""status"":""rest""},{""status"":""rest""},{""status"":""common""},{""status"":""relax""},{""status"":""normal""}]";


            string json_strtest2 = @"[[{""up"":[]},{""down"":[]}],[{""up"":[]},{""down"":[]}],[{""up"":[]},{""down"":[]}],[{""up"":[{""eventCode"":""thinking"",""index"":1}]},{""down"":[]}],[{""up"":[{""eventCode"":""thinking"",""index"":1}]},{""down"":[]}]]";
            string status_test2 = @"[{""status"":""-1""},{""status"":""-1""},{""status"":""-1""},{""status"":""common""},{""status"":""-1""}]";



         string resultX=   CsharpScript.get_period_data(status_test2, json_strtest2);

            Console.WriteLine(resultX);

            //   CsharpScript.get_period_data(status_total_json, json_stringAll,allOneMinutesList,false);

            //  CsharpScript.get_period_data(status_period_json, json_string);
            //  CsharpScript.get_period_data(status_period_json, json_string);


        }

    }

   public static class CsharpScript
    {
        #region LoadConfiguration

        /// <summary>
        /// 指标分析配置
        /// </summary>
        static AnalysisConfiguration AnalysisConfiguration { get; set; }

        /// <summary>
        /// 因子配置
        /// </summary>
        static List<FactorConfiguration> FactorConfigurations { get; set; }

        /// <summary>
        /// 模型配置
        /// </summary>
        static List<ModelConfiguration> ModelConfigurations { get; set; }

        /// <summary>
        /// 加载配置
        /// </summary>
        /// <param name="analysisConfiguration">指标分析配置json</param>
        /// <param name="factorConfiguration">因子配置json</param>
        /// <param name="modelConfiguration">模型配置json</param>
        /// <returns></returns>
        public static bool LoadConfiguration(string analysisConfiguration, string factorConfiguration, string modelConfiguration)
        {
            try
            {
                AnalysisConfiguration = JsonConvert.DeserializeObject<AnalysisConfiguration>(analysisConfiguration);
                FactorConfigurations = JsonConvert.DeserializeObject<List<FactorConfiguration>>(factorConfiguration);
                ModelConfigurations = JsonConvert.DeserializeObject<List<ModelConfiguration>>(modelConfiguration);

              //  parse_status_data();





                foreach (var factor in FactorConfigurations)
                {
                    // 无标准分级的时候，默认为0
                    if (string.IsNullOrEmpty(factor.standard))
                    {
                        factor.standards = new List<double>();
                        factor.results = JsonConvert.DeserializeObject<List<string>>(factor.result).Cast<object>().ToList();
                    }
                    else
                    {
                        // 按‘｜’对字符串进行分割
                        string[] standards = factor.standard.Split('|');
                        string[] results = factor.result.Split('|');
                        // 标准和结果个数不匹配，返回false，结果应该比标准多一个
                        if (standards.Length != results.Length - 1)
                        {
                            return false;
                        }
                        factor.standards = standards.Select(double.Parse).ToList();

                        factor.results = new List<object>();
                        // 循环将标准和结果作为键值对放入字典
                        for (int i = 0; i < results.Length; i++)
                        {
                            // 尝试解析成整数（等级）
                            if (int.TryParse(results[i], out int result))
                            {
                                factor.results.Add(result);
                            }
                            else  // 解析成字符串数组
                            {
                                factor.results.Add(JsonConvert.DeserializeObject<List<string>>(results[i]));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }                
   
          //  parse_status_for_Total();
            return true;
        }

        #endregion

        #region  阶段或总评

        //所有的二级指标模型     
         static Dictionary<string, CRule> neededRule = new Dictionary<string, CRule>();
        static string periodStatus = string.Empty;
         static Random random = new Random();

         static int GroupCounts = 0;

        /// <summary>
        /// 存放二级指标对应的levle全局变量,value 为list<int>>
        /// </summary>
        static Dictionary<string, List<int>> globalDataDicTotal = new Dictionary<string, List<int>>();
        static string totalStatus = string.Empty;

        static string TempStatus = string.Empty;

        //状态列表
         static List<string> status = new List<string>();

        //修改的状态变量 
         static Dictionary<string, List<string>> statusNew = new Dictionary<string, List<string>>();

         static List<string> up_event = new List<string>();
         static List<string> down_event = new List<string>();
        //"statusCodes":["positive","serious","normal","common","relax","rest"],"statusScore":[6,5,4,3,2,1],
         static List<string> status_codes = new List<string>();
         static List<int> status_score = new List<int>();       

         static Dictionary<string, string> variables = new Dictionary<string, string>();
         static List<string> randoms = new List<string>();
         static Dictionary<string, string> none_opts = new Dictionary<string, string>();
         static string offline_des = "期间出现较长时间断线，评估结果仅供参考。";
         static Dictionary<string, double> parametersTotalResult = new Dictionary<string, double>();

        /// <summary>
        /// 计算 精力水平  大脑活动  情绪特质   
        /// </summary>
        /// <param name="someIndex"></param>
        /// <param name="formula"></param>
        /// <returns></returns>
         static double EvaluateTotalFormula(string someIndex, string formula)
        {
            // Evaluate the formula and return the score

            Expression e = new Expression(formula, EvaluateOptions.IgnoreCase);

            foreach (string item in parametersTotalResult.Keys)
            {
                e.Parameters[item] = parametersTotalResult[item];
            }
            var result = e.Evaluate();


            return (double)result;
        }


        public static string get_period_data(string status_json, string events_json, string analysis_json = "", bool stage = true)
        {
            try
            {
                //先清
                status.Clear();
                up_event.Clear();
                down_event.Clear();
                none_opts.Clear();
                randoms.Clear();

                if (stage)
                {
                    if (string.IsNullOrWhiteSpace(AnalysisConfiguration.periodStatusCode))
                    {
                        return string.Empty;
                    }
                    //返回的字符串的总模板
                    var statusPeriod = ModelConfigurations?.SingleOrDefault(t => t.code.Equals(AnalysisConfiguration.periodStatusCode));
                    periodStatus = statusPeriod.related_cfactors.ToString();
                   // parse_status_for_Total();

                    TempStatus = periodStatus;
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(AnalysisConfiguration.totalStatusCode))
                    {
                        return string.Empty;
                    }
                 //   parse_status_for_Total();

                    neededRule.Clear();
                    List<string> lastResultFactors = new List<string>();
                    //返回的字符串的总模板
                    var statusTotal = ModelConfigurations?.SingleOrDefault(t => t.code.Equals(AnalysisConfiguration.totalStatusCode));
                    totalStatus = statusTotal.related_cfactors.ToString();

                    // 使用正则表达式匹配大括号中的内容
                    string pattern = @"\{([^{}]*)\}";
                    MatchCollection matches = Regex.Matches(totalStatus, pattern);

                    // 遍历匹配结果，并根据关键词提取相关部分
                    foreach (Match match in matches)
                    {
                        string content = match.Groups[1].Value;
                        var about = FactorConfigurations.SingleOrDefault(t => t.code == content);
                        if (about != null && !string.IsNullOrEmpty(about.formula))
                        {
                            lastResultFactors.Add(content);
                        }                       
                    }

                    foreach (var item in lastResultFactors)
                    {
                        var Level2Factor = FactorConfigurations?.SingleOrDefault(t => t.code.Equals(item));
                        neededRule.Add(item, new CRule()
                        {
                            standard = Level2Factor.standard,
                            result = Level2Factor.result,
                            formula = Level2Factor.formula,
                        }
                                     );
                    }
                    parametersTotalResult.Clear();
                   // parse_indicator_value(analysis_json);
                    globalDataDicTotal = JsonConvert.DeserializeObject<Dictionary<string, List<int>>>(analysis_json);
                   
                    TempStatus = totalStatus;
                }             

                var offline_status = ParseStatus(status_json);
                if (offline_status == "long_offline")
                {
                    var result333_json = new Dictionary<string, string> { { "period_des", "断线时间较长，不做评价" } };
                 //   Console.WriteLine(result333_json["period_des"]); 
                    return result333_json["period_des"];
                }
                else
                {
                    ParseEvent(status_json, events_json);
                }

                CalculateKeyEvent(GroupCounts);
                CalculateExtEvent(GroupCounts);

                //TempStatus已更新

              //  Console.WriteLine(TempStatus);

                ParseSetting();
                if (stage)
                {
                    //更新状态和状态趋势
                    
                    foreach (var item in statusNew.Keys)
                    {
                        //更新 
                        status_codes = AnalysisConfiguration.statusModels[item];

                        if (status_codes.Contains("-1"))
                        {
                            status_codes.Remove("-1");
                        }
                        if (status_score.Count != 0)
                        {
                            status_score.Clear();
                        }
                        //  var sModelScore = FactorConfigurations?.SingleOrDefault(t => t.code.Equals("statusScore"));

                        var sModelScore = FactorConfigurations?.SingleOrDefault(t => t.code.Equals(item + "Score"));

                        List<double> paraScores3 = sModelScore.standards;  //list<Score>

                        List<object> paraStatusStr3 = sModelScore.results;

                        List<string> paraScores = sModelScore.standard.Split('|').ToList();  //list<Score>


                        List<string> paraStatusStr = new List<string>();

                        foreach (object itemX in paraStatusStr3)
                        {
                            paraStatusStr.Add(((List<string>)itemX)[0]);
                        }
                        List<int> scoreList = paraScores.ConvertAll(int.Parse);

                        for (int i = 0; i < status_codes.Count; i++)
                        {

                            for (int j = 0; j < paraStatusStr.Count; j++)
                            {
                                if (status_codes[i] == paraStatusStr[j])
                                {
                                    status_score.Add(scoreList[j]);
                                    break;
                                }
                            }
                        }

                        CalculateStatus(item);
                    }
                }
                else
                {
                    //更新 第二段中的三个因子和因子趋势
                    foreach (string itemX in neededRule.Keys)
                    {
                        CalculateCfactorTotal(itemX, neededRule);
                    }

                    foreach (var item in statusNew.Keys)
                    {
                        //更新 
                        status_codes = AnalysisConfiguration.statusModels[item];

                        if (status_codes.Contains("-1"))
                        {
                            status_codes.Remove("-1");
                        }
                        if (status_score.Count != 0)
                        {
                            status_score.Clear();
                        }
                        //  var sModelScore = FactorConfigurations?.SingleOrDefault(t => t.code.Equals("statusScore"));

                        var sModelScore = FactorConfigurations?.SingleOrDefault(t => t.code.Equals(item + "Score"));

                        List<double> paraScores3 = sModelScore.standards;  //list<Score>

                        List<object> paraStatusStr3 = sModelScore.results;

                        List<string> paraScores = sModelScore.standard.Split('|').ToList();  //list<Score>


                        List<string> paraStatusStr = new List<string>();

                        foreach (object itemX in paraStatusStr3)
                        {
                            paraStatusStr.Add(((List<string>)itemX)[0]);
                        }
                        List<int> scoreList = paraScores.ConvertAll(int.Parse);

                        for (int i = 0; i < status_codes.Count; i++)
                        {

                            for (int j = 0; j < paraStatusStr.Count; j++)
                            {
                                if (status_codes[i] == paraStatusStr[j])
                                {
                                    status_score.Add(scoreList[j]);
                                    break;
                                }
                            }
                        }

                        //  CalculateStatus(item);
                    }
                    //更新状态和状态趋势
                    CalculateStatus("total");
                }               


                var model_code3 = TempStatus;

                var model_code = TempStatus;
                
                var final_result = model_code;
                

                foreach (var variable in variables)
                {
                    final_result = final_result.Replace("{" + variable.Key + "}", variable.Value);
                }

                if (offline_status == "part_offline")
                {
                    final_result = final_result + offline_des;
                }
                var result_json = new Dictionary<string, string> { { "period_des", final_result } };
               // Console.WriteLine(result_json["period_des"]);

                return result_json["period_des"];
            }
            catch (Exception e)
            {
              //  Console.WriteLine("fail");
                return "fail";
            }

            return string.Empty;
        }

     

         static string GetRandom(string result)
        {           

            //   List<string> list_result = result.Split(',').ToList();
            List<string> list_result = JsonConvert.DeserializeObject<List<string>>(result);
            if (randoms.Count > 0)
            {
                var var = list_result.Except(randoms).ToList();
                if (var.Count == 0)
                {
                    var value = list_result[random.Next(list_result.Count)];
                    return value;
                }
                else
                {
                    var value = var[random.Next(var.Count)];
                    return value;
                }
            }
            else
            {
                var value = list_result[random.Next(list_result.Count)];
                randoms.Add(value);
                return value;
            }
        }
       

         static void GetTrend(string variable, float slope)
        {
            var trend1 = FactorConfigurations?.SingleOrDefault(t => t.code.Equals(variable + "_trend"));
            var standard = trend1.standard.Split('|').ToList();
            var result = trend1.result.Split('|').ToList();        

            
            var final_result = "";
            for (int i = 0; i < standard.Count; i++)
            {
                if (slope <= float.Parse(standard[i]))
                {
                    final_result = result[i];
                    break;
                }
            }
            if (final_result == "")
            {
                final_result = result[result.Count - 1];
            }
            variables[variable + "_trend"] = GetRandom(final_result);   //插入字典项 
        }

         static string GetFrequence(float frequence)
        {
            //var trend = setting_data["frequence"];
            var trend = FactorConfigurations?.SingleOrDefault(t => t.code.Equals("frequence")); 

            var standard = trend.standard.Split('|').ToList();
            var result = trend.result.Split('|').ToList();
            var final_result = "";
            for (int i = 0; i < standard.Count; i++)
            {
                if (frequence <= float.Parse(standard[i]))
                {
                    final_result = result[i];
                    break;
                }
            }
            if (final_result == "")
            {
                final_result = result[result.Count - 1];
            }
            //var xx = FactorConfigurations?.SingleOrDefault(t => t.code.Equals("totaldes")).result.Replace("\"", "").Replace("[", "").Replace("]", "");
            return GetRandom(final_result);
        }

         static void CalculateStatus( string stageStr)
        {

            var status_dict = status_codes.Zip(status_score, (k, v) => new { k, v }).ToDictionary(x => x.k, x => x.v);

            var total_score = status.Sum(s => status_dict[s]);

            int  average_score =(int) Math.Round((float)total_score / status.Count,MidpointRounding.AwayFromZero);


            //  var status_slope = (status_dict[status.Last()] - status_dict[status.First()])*1.0f / status.Count;

            List<double> listY = new List<double>();
            List<double> listX = new List<double>();
       
            for (int i = 0;  i < status.Count; i++)
            {                
                listY.Add(status_dict[status[i]]);
                listX.Add(i+1);
            }

            double status_slope = 0;
            if (listY.Count <2)
            {
                status_slope = 0;
            }
            else
            {
                status_slope = MathNet.Numerics.Fit.Line(listY.ToArray(), listX.ToArray()).B;
            }
            


            var final_status = status_dict.FirstOrDefault(x => x.Value == average_score).Key;
            variables["status"] = final_status;      //字典变量插入或更新         
           
            GetTrend(stageStr, (float)status_slope);           

        }

         static void CalculateKeyEvent(int groupCounts)
        {
            var counter = up_event.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());

            var most_common_three = counter.OrderByDescending(x => x.Value).Take(3).ToList();
            if (most_common_three.Count == 0)
            {
                none_opts["key_event"] = "1";              

                var start_index = TempStatus.IndexOf("其中");
                var end_index = TempStatus.IndexOf("，", start_index);
                TempStatus = TempStatus.Substring(0, start_index - 1) + TempStatus.Substring(end_index);
                return;
            }
            var keys = new List<string>();
            var total_count = groupCounts;
            foreach (var item in most_common_three)
            {
                var pctg = (float)item.Value / total_count * 100;
                keys.Add(GetFrequence(pctg) + "的{" + item.Key + "}");
            }
            var result = string.Join("、", keys);
            variables["keyevent"] = result;
            TempStatus = TempStatus.Replace("{" + "keyevent" + "}", variables["keyevent"]);  

        }

         static void CalculateExtEvent(int groupCounts)
        {

            var counter = down_event.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
            var most_common_three = counter.OrderByDescending(x => x.Value).Take(3).ToList();
            if (most_common_three.Count == 0)
            {
                none_opts["ext_event"] = "1";
                var start_index = TempStatus.IndexOf("并伴随");
                //  TempStatus = TempStatus.Substring(0, start_index - 1) + TempStatus.Substring(start_index + 3);
                TempStatus = TempStatus.Substring(0, start_index - 1)+ TempStatus.Substring(start_index + 3);
                TempStatus = TempStatus.Replace("{" + "extevent" + "}", string.Empty);
                return;
            }

            var keys = new List<string>();
            var total_count = groupCounts;
            foreach (var item in most_common_three)
            {
                var pctg = (float)item.Value / total_count * 100;
                keys.Add(GetFrequence(pctg) + "的{" + item.Key + "}");
            }
            var result = string.Join("、", keys);
            variables["extevent"] = result;
            TempStatus = TempStatus.Replace("{" + "extevent" + "}", variables["extevent"]);
        }


         static string ParseStatus(string status_json )
        {
            var count = 0;
            List <Dictionary<string, string> > statusDictList = new List<Dictionary<string, string>>();
            statusDictList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(status_json);


            List<string> keys = statusDictList.First().Keys.ToList();
            foreach (var key in keys)
            {
                statusNew[key] = statusDictList.Select(t => t[key]).ToList();
                 count = statusNew[key].Count(t => t.Equals("-1"));
            } 

            status = statusNew[statusNew.First().Key];
            var percetage = (statusNew.First().Value.Count-count)* 100 / statusNew.First().Value.Count;
            status = status.Where(s1 => s1 != "-1").ToList();
            if (percetage < 10)
            {
                return "long_offline";
            }
            else if (percetage < 50)
            {
                return "part_offline";
            }
            else
            {
                return "";
            }
        }

         static void  ParseEvent(string status_json, string events_json)
        {    
            //Parse Event 
            List<List<EventPoints>> eventPoints = JsonConvert.DeserializeObject<List<List<EventPoints>>>(events_json);

            GroupCounts = eventPoints.Count;

            foreach (var item in eventPoints)   //具体的一个三分钟的集合
            {
                foreach (var data in item)
                {
                    if (data.up != null)
                    {
                        foreach (var itemUp in data.up)
                        {
                            up_event.Add(itemUp.eventCode);
                        }
                    }

                    if (data.down != null)
                    {
                        foreach (var itemDown in data.down)
                        {
                            down_event.Add(itemDown.eventCode);
                        }
                    }
                }
            }
       
        }

         static void ParseSetting()
        {
            foreach (var factor in FactorConfigurations)
            {
                if (string.IsNullOrEmpty(factor.standard))
                {
                    variables[factor.code] = GetRandom(FactorConfigurations?.SingleOrDefault(t => t.code.Equals(factor.code)).result);                  
                }
            }
        }       

         static void CalculateCfactorTotal(string variable, Dictionary<string, CRule> modelSettingData)
        {                      

            foreach (var item in globalDataDicTotal.Keys)
            {
                //更新[二级指标名] 对应 的list<i>
                var filteredNumbers = globalDataDicTotal[item].Where(n => n != -1).ToList();
                //更新 
                globalDataDicTotal[item]= filteredNumbers;

                double average = filteredNumbers.Average();
                parametersTotalResult[item] = average;            }

            double score = EvaluateTotalFormula(variable, modelSettingData[variable].formula);

            List<string> standard = modelSettingData[variable].standard.Split('|').ToList();
            List<string> result = modelSettingData[variable].result.Split('|').ToList();
            string final_result = "";
            for (int i = 0; i < standard.Count; i++)
            {
                if (score <= double.Parse(standard[i]))
                {
                    final_result = result[i];
                    break;
                }
            }
            if (final_result == "")
            {
                final_result = result[result.Count - 1];
            }

            variables[variable] = GetRandom(final_result);

            List<double> listY = new List<double>();
            List<double> listX = new List<double>();

          
            for (int i = 0; i < globalDataDicTotal.First().Value.Count; i++)
            {
                foreach (var item in globalDataDicTotal.Keys)
                {
                    //更新[二级指标名] 对应 的list<i>
                    parametersTotalResult[item] = globalDataDicTotal[item][i];
                }

                var tempScore= EvaluateTotalFormula(variable, modelSettingData[variable].formula);

                listY.Add(tempScore);
                listX.Add(i + 1);

            }

            double status_slope = 0;
            if (listY.Count < 2)
            {
                status_slope = 0;
            }
            else
            {
                status_slope = MathNet.Numerics.Fit.Line(listY.ToArray(), listX.ToArray()).B;
            }

          //  double status_slope = MathNet.Numerics.Fit.Line(listY.ToArray(), listX.ToArray()).B;

            Debug.WriteLine(status_slope.ToString());
            GetTrend(variable,(float) status_slope);
        }
        #endregion
    }

    /// <summary>
    /// 指标分析配置
    /// </summary>
    public class AnalysisConfiguration
    {
      
        /// <summary>
        /// 二级指标
        /// </summary>
        public List<string> analysisModels { get; set; }
        /// <summary>
        /// 状态指标
        /// </summary>
        public Dictionary<string, List<string>> statusModels { get; set; }
        /// <summary>
        /// 事件点
        /// </summary>
        public Dictionary<string, List<string>> eventPoints { get; set; }
        /// <summary>
        /// 阶段评价code
        /// </summary>
        public string periodStatusCode { get; set; }
        /// <summary>
        /// 总评code
        /// </summary>
        public string totalStatusCode { get; set; }
    }

    /// <summary>
    /// 因子配置
    /// </summary>
    public class FactorConfiguration
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string name { get; set; }
        /// <summary>
        /// 唯一编码
        /// </summary>
        public string code { get; set; }
        /// <summary>
        /// 公式
        /// </summary>
        public string formula { get; set; }
        /// <summary>
        /// 标准
        /// </summary>
        public string standard { get; set; }
        /// <summary>
        /// 结果
        /// </summary>
        public string result { get; set; }
        /// <summary>
        /// 范式
        /// </summary>
        public string pattern { get; set; }
        /// <summary>
        /// 标准列表
        /// </summary>
        public List<double> standards { get; set; }
        /// <summary>
        /// 结果列表
        /// </summary>
        public List<object> results { get; set; }
    }

    /// <summary>
    /// 模型配置
    /// </summary>
    public class ModelConfiguration
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string name { get; set; }
        /// <summary>
        /// 唯一编码
        /// </summary>
        public string code { get; set; }
        /// <summary>
        /// 关联因子
        /// </summary>
        public object related_cfactors { get; set; }
    }


    public class EventDetail
    {
        public string eventCode { get; set; }
        public int index { get; set; }
    }

    //状态列表 

    public class EventPoints
    {
        public List<EventDetail> up { get; set; }
        public List<EventDetail> down { get; set; }
    }


    public class CRule
    {
        public string standard { get; set; }
        public string result { get; set; }
        public string formula { get; set; }
    }


}
